<template>
  <div class="login-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="用户登录"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 登录表单区域 -->
    <div class="login-content">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo-icon">
          <van-icon name="user-circle-o" size="80" color="#1989fa" />
        </div>
        <h1 class="app-title">智慧医疗平台</h1>
        <p class="app-subtitle">便民医疗服务，健康生活从这里开始</p>
      </div>

      <!-- 登录表单 -->
      <div class="login-form">
        <van-form @submit="onSubmit">
          <!-- 用户名/手机号输入 -->
          <van-cell-group inset class="form-fields">
            <van-field
              v-model="loginForm.username"
              name="username"
              label="账号"
              placeholder="请输入用户名或手机号"
              left-icon="contact"
              :rules="usernameRules"
              clearable
              class="input-field"
            />
            
            <!-- 密码输入 -->
            <van-field
              v-model="loginForm.password"
              type="password"
              name="password"
              label="密码"
              placeholder="请输入密码"
              left-icon="lock"
              :rules="passwordRules"
              clearable
              class="input-field"
            />
          </van-cell-group>

          <!-- 记住密码和忘记密码 -->
          <div class="login-options">
            <van-checkbox v-model="rememberPassword">记住密码</van-checkbox>
            <van-button type="primary" plain size="mini" @click="forgotPassword">
              忘记密码？
            </van-button>
          </div>

          <!-- 登录按钮 -->
          <div class="login-button">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
              loading-text="登录中..."
              size="large"
            >
              登录
            </van-button>
          </div>
        </van-form>

        <!-- 其他登录方式 -->
        <div class="other-login">
          <div class="divider">
            <span>其他登录方式</span>
          </div>
          <div class="social-login">
            <van-button
              icon="wechat"
              type="success"
              round
              size="large"
              @click="wechatLogin"
            >
              微信登录
            </van-button>
          </div>
        </div>

        <!-- 注册链接 -->
        <div class="register-link">
          <span>还没有账号？</span>
          <van-button type="primary" plain size="mini" @click="goToRegister">
            立即注册
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import { apiService, type LoginRequest } from '@/api/index'
import { useUserStore } from '@/stores/user'

/**
 * 登录页面组件
 * 提供用户登录功能，支持用户名/手机号登录
 */

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const rememberPassword = ref(false)

/**
 * 登录表单数据
 */
const loginForm = reactive({
  username: '',
  password: ''
})

/**
 * 用户名验证规则
 */
const usernameRules = [
  { required: true, message: '请输入用户名或手机号' },
  { 
    validator: (value: string) => {
      // 验证手机号格式或用户名格式
      const phoneRegex = /^1[3-9]\d{9}$/
      const usernameRegex = /^[a-zA-Z0-9_]{4,20}$/
      return phoneRegex.test(value) || usernameRegex.test(value)
    }, 
    message: '请输入正确的手机号或用户名（4-20位字母数字下划线）' 
  }
]

/**
 * 密码验证规则
 */
const passwordRules = [
  { required: true, message: '请输入密码' },
  { min: 6, message: '密码长度不能少于6位' }
]

/**
 * 返回上一页
 */
const onClickLeft = () => {
  router.back()
}

/**
 * 提交登录表单
 */
const onSubmit = async (values: any) => {
  loading.value = true
  
  try {
    // 构造登录请求数据
    const loginData: LoginRequest = {
      userName: values.username,
      password: values.password
    }
    
    // 调用后端登录API
    const response = await apiService.login(loginData)
    
    // 检查登录结果
    if (response.code === 200) {
      // 登录成功
      Toast.success(response.message || '登录成功！')
      
      // 保存登录信息（包括记住密码功能）
      saveLoginData(values.username, values.password)
      
      // 使用用户状态管理保存用户信息
      userStore.setUserInfo(response.data)
      
      // 跳转到目标页面或首页
      setTimeout(() => {
        const redirect = router.currentRoute.value.query.redirect as string
        if (redirect && redirect !== '/login') {
          router.replace(redirect)
        } else {
          router.replace('/home')
        }
      }, 1000)
    } else {
      // 登录失败
      Toast.fail(response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    Toast.fail('网络连接失败，请检查后端服务是否启动')
  } finally {
    loading.value = false
  }
}

/**
 * 忘记密码
 */
const forgotPassword = () => {
  Dialog.alert({
    title: '忘记密码',
    message: '请联系管理员重置密码，或通过手机验证码找回密码。\n\n客服电话：400-123-4567',
    confirmButtonText: '我知道了'
  })
}

/**
 * 微信登录
 */
const wechatLogin = () => {
  Toast('微信登录功能开发中...')
}

/**
 * 跳转到注册页面
 */
const goToRegister = () => {
  router.push('/register')
}

/**
 * 页面初始化时检查是否有记住的登录信息
 */
const initRememberedData = () => {
  const rememberedData = localStorage.getItem('rememberedLoginData')
  if (rememberedData) {
    try {
      const data = JSON.parse(rememberedData)
      loginForm.username = data.username || ''
      loginForm.password = data.password || ''
      rememberPassword.value = true
    } catch (error) {
      console.error('解析记住的登录信息失败:', error)
      localStorage.removeItem('rememberedLoginData')
    }
  }
}

/**
 * 保存登录信息到本地存储
 */
const saveLoginData = (username: string, password: string) => {
  if (rememberPassword.value) {
    // 简单的Base64编码（实际项目中应使用更安全的加密方式）
    const encodedData = {
      username: btoa(username),
      password: btoa(password)
    }
    localStorage.setItem('rememberedLoginData', JSON.stringify(encodedData))
  } else {
    localStorage.removeItem('rememberedLoginData')
  }
}

/**
 * 从本地存储获取登录信息
 */
const getLoginData = () => {
  const rememberedData = localStorage.getItem('rememberedLoginData')
  if (rememberedData) {
    try {
      const data = JSON.parse(rememberedData)
      return {
        username: atob(data.username || ''),
        password: atob(data.password || '')
      }
    } catch (error) {
      console.error('解析记住的登录信息失败:', error)
      localStorage.removeItem('rememberedLoginData')
    }
  }
  return null
}

// 初始化记住的数据
initRememberedData()
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.login-content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding-top: 20px;
  min-height: calc(100vh - 46px); /* 减去导航栏高度 */
}

/* Logo区域样式 */
.logo-section {
  text-align: center;
  margin-bottom: 24px;
  padding-top: 10px;
}

.logo-icon {
  margin-bottom: 12px;
}

.app-title {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin-bottom: 6px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.app-subtitle {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
  margin-bottom: 0;
}

/* 登录表单样式 */
.login-form {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

/* 表单字段样式 */
.form-fields {
  margin-bottom: 0;
}

.input-field {
  --van-field-label-width: 60px;
  margin-bottom: 12px;
}

/* 调整输入框高度和内边距 */
.input-field :deep(.van-field) {
  padding: 16px 12px;
  min-height: 56px;
}

.input-field :deep(.van-field__label) {
  width: 60px;
  min-width: 80px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.4;
}

.input-field :deep(.van-field__body) {
  flex: 1;
  min-width: 0;
}

.input-field :deep(.van-field__body) {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
}

.input-field :deep(.van-cell) {
  padding: 16px 12px;
  align-items: center;
  min-height: 56px;
}

.input-field :deep(.van-field__control) {
  flex: 1;
  min-width: 0;
  padding-left: 8px;
}

.input-field :deep(.van-field__control input) {
  width: 100%;
  box-sizing: border-box;
  padding: 8px 0;
  margin: 0;
  border: none;
  outline: none;
  background: transparent;
  font-size: 16px;
  height: 24px;
  line-height: 1.5;
}

/* 修复placeholder样式，确保提示词完整显示 */
.input-field :deep(.van-field__control input::placeholder) {
  color: #c8c9cc;
  font-size: 14px;
  line-height: 1.5;
  white-space: nowrap;
  overflow: visible;
  text-overflow: ellipsis;
  opacity: 1;
}

/* 修复密码输入框错位问题 */
.input-field :deep(.van-field__control input[type="password"]) {
  line-height: normal;
  vertical-align: baseline;
  font-family: inherit;
  text-indent: 0 !important;
  padding-left: 0 !important;
  margin-left: 0 !important;
  transform: none !important;
  position: relative;
  left: 0 !important;
}

/* 防止浏览器自动填充样式影响 */
.input-field :deep(.van-field__control input:-webkit-autofill) {
  -webkit-text-fill-color: inherit !important;
  -webkit-box-shadow: 0 0 0 1000px transparent inset !important;
  transition: background-color 5000s ease-in-out 0s;
  text-indent: 0 !important;
  padding-left: 0 !important;
  margin-left: 0 !important;
}

/* 确保所有输入框样式一致 */
.input-field :deep(.van-field__control input) {
  text-indent: 0 !important;
  padding-left: 0 !important;
  margin-left: 0 !important;
  transform: none !important;
  position: relative;
  left: 0 !important;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 12px 0;
  padding: 0 4px;
}

.login-button {
  margin: 20px 0 16px 0;
}

/* 其他登录方式样式 */
.other-login {
  margin-top: 16px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 16px 0;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #ebedf0;
}

.divider span {
  background: white;
  padding: 0 16px;
  font-size: 12px;
  color: #969799;
}

.social-login {
  margin-top: 12px;
}

/* 注册链接样式 */
.register-link {
  text-align: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebedf0;
  font-size: 14px;
  color: #646566;
}

.register-link span {
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .login-content {
    padding: 12px;
    padding-top: 16px;
  }
  
  .login-form {
    padding: 16px;
  }
  
  .logo-section {
    margin-bottom: 20px;
    padding-top: 8px;
  }
  
  .app-title {
    font-size: 22px;
  }
  
  .app-subtitle {
    font-size: 12px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .login-form {
    background: #1e1e1e;
    color: white;
  }
  
  .divider::before {
    background: #333;
  }
  
  .divider span {
    background: #1e1e1e;
    color: #999;
  }
}
</style>